﻿#include <iostream>
#include "core/app_manager.h"
#include "core/async_listener.h"

using namespace vz;

class App1 : public AppInterface,
  public sigslot::has_slots<> {
 public:
  typedef scoped_refptr<App1> Ptr;
  App1(const std::string& app_name)
    : AppInterface(app_name) {
  }

  bool OnPreInit() {
    LOG(LS_INFO) << "OnPreInit";
    return true;
  }

  bool OnInit() {
    LOG(LS_INFO) << "OnInit";
    return true;
  }

  bool OnRun() {
    LOG(LS_INFO) << "OnRun";

    socket_ = event_service_->CreateSocket();
    socket_->SignalConnectEvent.connect(this, &App1::OnConnectEvent);
    SocketAddress address("127.0.0.1", 6756);
    socket_->Connect(address);
    return true;
  }

  void OnAppMessage(Message* msg) {
    LOG(LS_INFO) << "OnAppMessage";
  }

 private:
  void OnConnectEvent(AsyncPacketSocket::Ptr socket) {
    LOG(LS_INFO) << "Socket connected!";
    socket->SignalPacketEvent.connect(this, &App1::OnPacketEvent);
    socket->SignalCloseEvent.connect(this, &App1::OnCloseEvent);
    socket->SendPacket(1);
  }

  void OnPacketEvent(AsyncPacketSocket::Ptr socket, uint16 cmd, const char* data, uint32 data_size) {
    if (cmd == 2) {
      LOG(LS_INFO) << "New packet: " << data_size;
    }
  }

  void OnCloseEvent(AsyncPacketSocket::Ptr socket, int error) {
    LOG(LS_ERROR) << "Socket closed! error: " << error;
    socket_.release();
  }

 private:
  AsyncPacketSocket::Ptr socket_;
};

int main(int argc, char *argv[]) {
  AppManager::Ptr manager(new RefCountedObject<AppManager>());
  App1::Ptr app1(new RefCountedObject<App1>("App1"));
  manager->Register(app1);

  manager->Run();

  return 0;
}
